package com.openread.tools;

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

public class HttpUtil {

    private static HttpClientHelper hHelper = new HttpClientHelper(false);

    public static Header[] makeGenHeaders() {
        return new Header[] {
                new BasicHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"),
                new BasicHeader(
                        "User-Agent",
                        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36"),
                new BasicHeader("Accept-Encoding", "gzip,deflate,sdch"),
                new BasicHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6"),
                new BasicHeader("Connection", "keep-alive") };
    }

    public static String sendGet(String url, String charset, boolean isSSL) {
        CloseableHttpResponse response = null;
        try {
            HttpGet request = new HttpGet(url);
            CloseableHttpClient hclient = null;

            if (!url.contains("www.google.com")) {
                request.setHeaders(makeGenHeaders());
            }

            if (isSSL) {
                hclient = hHelper.createSSLClientDefault();
            } else {
                hclient = hHelper.getClient();
            }

            response = hclient.execute(request);
            return EntityUtils.toString(response.getEntity(), charset).trim();
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String args[]) throws Exception {
        System.out.println(sendGet("http://www.sina.com", "gb2312", true));
    }
}
